<?php

namespace app\admin\controller\setting;

use app\common\controller\Backend;

/**
 * QQ群
 *
 * @icon fa fa-circle-o
 */
class QqGroup extends Backend
{

    /**
     * QqGroup模型对象
     * @var \app\common\model\QqGroup
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\QqGroup;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','qq','nickname','createtime','join_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function config(){

        $row = \app\common\model\QqGroupConfig::find();
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            if(!$params['cookie'] || !$params['bkn']){
                $this->error(__('参数错误'));
            }

            if($row){
                $row->save($params);
            }else{
                \app\common\model\QqGroupConfig::create($params);
            }

            $this->success(__('修改成功'));
        }

        $this->assign('row',$row);
        return $this->view->fetch();
    }

    public function up(){
        $row = \app\common\model\QqGroupConfig::find();
        if(!$row['cookie'] || !$row['bkn'] || !$row['qun']){
            $this->error(__('未配置QQ信息'));
        }

        $list = send($row['cookie'],$row['qun'],$row['bkn']);
        if(false === $list){
            $this->error(__('配置已失效，请重新登录后重新复制保存'));
        }

        if(empty($list['mems'])){
            $this->error(__('配置已失效，请重新登录后重新复制保存'));
        }
        //获得总数据
        $sizeTotal = $list['count'];
        $p = ceil($sizeTotal / 20);
        for ($i=0;$i<$p;$i++)
        {
            //再次查询
            $size = $i * 20;
            $result = send($row['cookie'],$row['qun'],$row['bkn'],$size);
            if(empty($result['mems'])){
                $this->error(__('配置已失效，请重新登录后重新复制保存'));
                break;
            }
            foreach ($result['mems'] as $item)
            {
                //判断是否已经存在
                $count = \app\common\model\QqGroup::where('qq',$item['uin'])->count();
                if(!$count){
                    //写入QQ群
                    \app\common\model\QqGroup::create([
                        'qq'        => $item['uin'],
                        'join_time' => $item['join_time'],
                        'nickname'  => $item['nick']
                    ]);
                }
            }
        }
        $this->success(__('同步完成'));
    }
}


function send($cookie,$gc,$bkn,$st=0,$end=20){
    $curl = curl_init();
    $url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members";
    $postData = http_build_query([
        'gc' => $gc,
        'st' => $st,
        'end' => $end,
        'sort' => '0',
        'bkn' => $bkn, // 这里的 bkn 需要根据实际情况获取，可以通过查看浏览器开发工具获取
    ]);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($curl, CURLOPT_USERAGENT, "EOLINKER");
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
        'Cookie: ' . $cookie,
    ]);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    if ($response === false) {
        return false;
    }

    curl_close($curl);
    return json_decode($response,true);
}